package adminlte.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * 客户端(其他模块微服务或者第三方可信服务)认证服务类，验证客户端是否有效
 * @author ZHUFEIFEI
 */
@Slf4j
@Service
public class BaseClientDetailService implements ClientDetailsService {
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        log.info("client ===> {}", clientId);
        BaseClientDetails client = this.get(clientId);
        if (client == null) {
            throw new NoSuchClientException("No client exists with clientId : " + clientId);
        }
        return client;
    }

    private BaseClientDetails get(String clientId) {
        BaseClientDetails client = null;
        //数据库中查询
        if (clientId.startsWith("adminlte")) {
            client = new BaseClientDetails();
            client.setClientId(clientId);
            //noop 无操作，明文密码
            client.setClientSecret("{noop}123456");
            client.setAuthorizedGrantTypes(Arrays.asList("authorization_code",
                    "client_credentials", "refresh_token", "password", "implicit"));
            //client.setResourceIds();
            client.setScope(Arrays.asList("phone", "email"));
            client.setAuthorities(AuthorityUtils.createAuthorityList("client_role"));
            //access token 有效期1天
            client.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1));
            //refresh token 有效期1天
            client.setRefreshTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1));
            client.addAdditionalInformation("key", "value");
            client.setRegisteredRedirectUri(new HashSet<>(Arrays.asList("http://localhost:8080/login/oauth2/callback/" + clientId)));
        }
        return client;
    }
}
